package bgw

import (
	"errors"
	"fmt"
	"regexp"
)

// 从X-WSSE提取 App PasswordDigest Nonce Created

func ParseXWSSE(xWsse string) (result map[string]string, err error) {
	// 编写正则表达式进行匹配
	re := regexp.MustCompile(`App="([^"]*)"\s*,\s*PasswordDigest="([^"]*)"\s*,\s*Nonce="([^"]*)"\s*,\s*Created="([^"]*)"`)
	matches := re.FindStringSubmatch(xWsse)
	if len(matches) != 5 {
		err = errors.New("invalid xWsse")
		return
	}
	app := matches[1]
	passwordDigest := matches[2]
	nonce := matches[3]
	created := matches[4]
	result = map[string]string{
		"App":            app,
		"PasswordDigest": passwordDigest,
		"Nonce":          nonce,
		"Created":        created,
	}
	return
}

// Authorization中提取值
// WSSE realm="{AppID}", profile="AppToken", type="v1"

func ParseAuthorization(authorization string) (result map[string]string, err error) {
	re := regexp.MustCompile(`realm="([^"]*)"\s*,\s*profile="([^"]*)"\s*,\s*type="([^"]*)"`)
	matches := re.FindStringSubmatch(authorization)
	if len(matches) != 4 {
		err = errors.New("invalid authorization")
		return
	}
	realm := matches[1]
	profile := matches[2]
	_type := matches[3]
	result = map[string]string{
		"realm":   realm,
		"type":    _type,
		"profile": profile,
	}
	return
}

// 解析bodySign
// sign_type="HMAC-SHA256", signature="${请求Body内容签名}"

func ParseBodySign(body string) (result map[string]string, err error) {
	re := regexp.MustCompile(`sign_type="([^"]*)"\s*,\s*signature="([^"]*)"`)
	matches := re.FindStringSubmatch(body)
	if len(matches) != 3 {
		err = errors.New("invalid Body-Sign")
		return
	}
	signType := matches[1]
	signature := matches[2]
	result = map[string]string{
		"sign_type": signType,
		"signature": signature,
	}
	return
}

func formatXWSSE(app, digest, nonce, created string) string {
	_str := `AppToken App="%s", PasswordDigest="%s", Nonce="%s", Created="%s"`
	return fmt.Sprintf(_str, app, digest, nonce, created)
}

func formatBodySing(hashType, signature string) string {
	_str := `sign_type="%s", signature="%s"`
	return fmt.Sprintf(_str, hashType, signature)
}

func formatAuthorization(appid string) string {
	_str := `WSSE realm="%s", profile="AppToken", type="v1"`
	return fmt.Sprintf(_str, appid)
}
